#include "RecieveThread.h"
#include <QtConcurrent>


void RecieveThread::udpDataRecieve(int port,char* IPaddr)
{
    qDebug() << "revieveThread  ThreadID:"<<QThread::currentThreadId();
     //1.加载库
     WORD wVersionRequested = MAKEWORD(2, 2);
     WSADATA data;
     int err = WSAStartup(wVersionRequested, &data);
     if (err != 0) {
         qDebug() << "lib load failed";
         return;
     }
     if (LOBYTE(data.wVersion) != 2 || HIBYTE(data.wVersion) != 2) {
         qDebug() << "lib version error";
         WSACleanup();//卸载错误的库
         return;
     }else {
         qDebug() << "lib load successful";
     }

     m_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
     //阅读帮助文档了解具体含义，三个参数均为宏定义或枚举类型
     if (m_sock == INVALID_SOCKET) {
         qDebug() << "socket creat failed";
         WSACleanup();//卸载库
         return;
     }
     sockaddr_in addrUDPServer;
     addrUDPServer.sin_family = AF_INET;
     addrUDPServer.sin_port = htons(port);
     addrUDPServer.sin_addr.S_un.S_addr = inet_addr(IPaddr);
     err = bind(m_sock, (sockaddr*)&addrUDPServer, sizeof(addrUDPServer));
     if(err){
        qDebug() << "bind failed";
        return;
     }

    auto recieveThread = QtConcurrent::run([=](){            //recieveThread 没有实际作用，屏蔽warning
        char recvBuf[1024] = "";
        //服务端IP，这个端口号要与服务端绑定的一致

        while (!stopFlag)
        {
            int nRecvNum = recvfrom(m_sock, recvBuf, sizeof(recvBuf), 0, nullptr, nullptr);
            qDebug() << "Server " << inet_ntoa(addrUDPServer.sin_addr) << ":" << recvBuf;
            qDebug() << "revieveThread  ThreadID:"<<QThread::currentThreadId();
            for (int i = 0; i < nRecvNum; i++) {
                dataTemp->push(recvBuf[i]);
            }
        }

        closesocket(m_sock);
        WSACleanup();
    });
}
